package com.darren.euc.util;

import com.darren.euc.entity.Member;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by yanglas on 2018/3/11.
 */
public class MyBeanUtils {

    public static void copyPropertiesIgnoreNull(Object source, Object target) {
        //源，目标，忽略的字段
        BeanUtils.copyProperties(source,target,getNullPropertyNames(source));
    }
    private static String[] getNullPropertyNames (Object source) {
        //无状态引用，线程安全
         BeanWrapper src = new BeanWrapperImpl(source);
         PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for(PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null){
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
}
